# Title: 云鸽本地关单
# Params: text|multi_str|故障备件已经更换，检查无其他告警。租户验证正常, account|one_str|dwwulin
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
云鸽提单.py
Author: wen
Email:happiness.sq@foxmail.com
Created Time: 2024/3/13 10:31
"""
import socket
import base64
import json
import random
import re
import time
import requests
import warnings
import datetime
# 过滤特定警告
from urllib3.exceptions import InsecureRequestWarning

warnings.filterwarnings("ignore", message="Unverified HTTPS request", category=InsecureRequestWarning)


def is_port_open(host: str, port: int) -> bool:
    """检查指定的主机和端口是否开放"""
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.settimeout(3)  # 设置超时时间为 3 秒
        try:
            sock.connect((host, port))
            return True
        except (socket.timeout, socket.error):
            return False


class yun_ge:
    def __init__(self, log, text):
        """替换为自己的cookies,即可使用"""
        self.log = log
        self.text = text
        self.json_data = None
        self.taskId = None
        self.headers = {
            "accept": "*/*",
            "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "cache-control": "no-cache",
            "content-type": "application/json;charset=utf-8",
            "pragma": "no-cache",
            "sec-ch-ua": "\"Not A(Brand\";v=\"99\", \"Microsoft Edge\";v=\"121\", \"Chromium\";v=\"121\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0"
        }
        self.cookies = {
            "sso_t_name": "uniToken",
            "sso_t_value": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ7XCJpcFwiOlwiMTAuMi43Ny4zNFwiLFwibmFtZVwiOlwi5ZC05p6XXCIsXCJtb2JpbGVcIjpcIjE4Nzk4Nzk3MTkwXCIsXCJhY2NvdW50XCI6XCJkd3d1bGluXCIsXCJzdWJBY2NvdW50XCI6XCJkd3d1bGluXCJ9IiwibmJmIjoxNzI2NzM3NzI4LCJpc3MiOiJwb3J0YWwtc3Rld2FyZCIsImV4cCI6MTcyNjczNzc4OCwiaWF0IjoxNzI2NzM3NzI4LCJqdGkiOiJiOGU2MTM1M2Q5ZjE0ZDA2YjNkODg2YTI0ZDNiMTNhYSJ9.6yKTR5x5NXkSi5KuHfOb61m_A4DAdxQBmD_XabPeIlI"

        }
        self.urls = {
            '172.17.42.253': 28080,  # sdp_url
            '172.21.152.199': 10372  # zw_url
        }
        self.url = self.find_open_url()
        if not self.url:
            self.log('网络连接失败，无法继续执行。请检查网络')
            return
        today = datetime.datetime.now()
        self.date = today.strftime('%Y-%m-%d %H:%M:%S')
        self.next_day = (today + datetime.timedelta(days=20)).strftime('%Y-%m-%d %H:%M:%S')
        url = f"https://{self.url}/uc/sso/auth"
        params = {
            "code": "cDBIYktURmtPVS9UZ0pRd1Y0UG5vUT09",
            "service": "s",
            "type": "umsToken"
        }
        self.session = requests.Session()
        response = self.session.get(url, headers=self.headers, cookies=self.cookies, params=params, verify=False,
                                    timeout=10)
        self.log(response.json())
        if response.json()['token']:
            self.headers['authorization'] = "Bearer " + response.json()['token']
            self.token = "Bearer " + response.json()['token']
            self.log("获取token成功")
        else:
            self.log("获取token失败")

    def work_list(self):
        """获取工单列表"""
        json_data = {
            'pageBean': {
                'page': '1',
                'pageSize': '1000',
                'showTotal': 'true',
            },
        }
        response = self.session.post(
            f'https://{self.url}/runtime/runtime/task/v1/getTodoList',
            headers=self.headers,
            json=json_data,
            verify=False,
        )
        if response.status_code == 200:
            total = response.json()["total"]
            list_rows = response.json()['rows']
            list_rows.reverse()

            for i in list_rows:
                self.taskId = i['taskId']
                subject = i['subject']
                name = i['name']
                procDefName = i['procDefName']
                procInstId = i['procInstId']
                createDate = i['createDate']
                if procDefName == "系统事件跟踪":
                    if "一线运维处理" in name:
                        self.log("工单阶段：" + name + "工单创建时间: " + createDate + "  工单ID: " + str(
                            self.taskId) + "  工单标题: " + subject + "  工单类型: " + procDefName + "  工单状态: " + procInstId)
                        result = self.work_info()
                        if result:
                            self.work_colse(result)
                            # self.work_task()
                            self.log('等待10秒……')
                            time.sleep(10)
            self.log('处理完毕')

    def work_info(self):
        url = f"https://{self.url}/runtime/runtime/task/v1/taskDetailBo"
        params = {
            "taskId": self.taskId,
            "reqParams": ""
        }
        response = requests.get(url, headers=self.headers, params=params, verify=False)
        if response.status_code == 200:
            self.json_data = response.json()["data"]
            sjms = self.json_data['xtsjgzdx']['sjms']
            pattern = r"维保状态：(.*)"
            match = re.search(pattern, sjms)
            if match:
                result = match.group(1)
                if result == '新华三':
                    result = 'H3C'
                # self.log(result)
                return result
        return False

    def find_open_url(self):
        """根据端口开放情况选择 URL"""
        for host, port in self.urls.items():
            if is_port_open(host, port):
                return f'{host}:{port}'
        return None

    def work_colse(self, sjms):
        headers = {
            'accept': 'application/json, text/plain, */*',
            'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'authorization': self.token,
            'bpm-nonceid': 'Q7ZrisA7hsNhz8m/p9Lam8g1l2vgPhNHtB8bsUPvaf8=',
            'content-type': 'application/json;charset=UTF-8',
            'priority': 'u=1, i',
            'sec-ch-ua': '"Chromium";v="124", "Microsoft Edge";v="124", "Not-A.Brand";v="99"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0',
        }
        data = self.json_data
        sjclgcjjg = self.text
        self.log(sjclgcjjg)
        self.log(sjms)
        data['xtsjgzdx']['sjjjsj'] = self.date
        data['xtsjgzdx']['sjyy'] = "硬件故障"
        data['xtsjgzdx']['zrdw'] = sjms
        data['xtsjgzdx']['cpfw'] = "机架式PC服务器"
        data['xtsjgzdx']['ywyxsz'] = "0"
        data['xtsjgzdx']['sjclgcjjg'] = sjclgcjjg
        json_str = json.dumps(data)
        base64_text = base64.b64encode(json_str.encode()).decode()
        json_data = {
            'taskId': self.taskId,
            'actionName': 'agree',
            'destination': '',
            'files': '',
            'opinion': sjclgcjjg,
            'jumpType': '',
            'nodeUsers': '[]',
            'data': base64_text,
            'formType': 'inner',
        }

        response = self.session.post(
            f'https://{self.url}/runtime/runtime/task/v1/complete',
            headers=headers,
            json=json_data,
            verify=False,
        )
        self.log(response.json())
        self.log(response.status_code)

    def work_task(self):
        headers = {
            'accept': 'application/json, text/plain, */*',
            'authorization': self.token,
            'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'bpm-nonceid': 'Q7ZrisA7hsNhz8m/p9Lam8g1l2vgPhNHtB8bsUPvaf8=',
            'content-type': 'application/json;charset=UTF-8',
            'priority': 'u=1, i',
            'sec-ch-ua': '"Chromium";v="124", "Microsoft Edge";v="124", "Not-A.Brand";v="99"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0',
        }
        data = self.json_data
        headers['authorization'] = self.token
        json_str = json.dumps(data)
        base64_text = base64.b64encode(json_str.encode()).decode()
        json_data = {
            'taskId': self.taskId,
            'actionName': 'agree',
            'destination': '',
            'files': '',
            'opinion': self.text,
            'jumpType': '',
            'nodeUsers': '[]',
            'data': base64_text,
            'formType': 'inner',
        }

        response = self.session.post(
            f'https://{self.url}/runtime/runtime/task/v1/complete',
            headers=headers,
            json=json_data,
            verify=False,
        )
        self.log(response.json())
        self.log(response.status_code)


def main():
    print(_account)
    wen_work = yun_ge(_console, text)
    wen_work.work_list()

#
# if __name__ == '__main__':
#     log = print
#     text = "故障备件已经更换，检查无其他告警。租户验证正常"
#     wen_work = yun_ge(log,text)
#     wen_work.work_list()
